package com.cdqidi.core.weixinmanager.service.wx;

import com.cdqidi.exception.ApiException;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.wxaapp.api.WxaMaterialApi;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WxService {


    private static final String TEXT_MSG = "点击放大二维码图片，长按关注公众号，打开提醒功能：";
    private static final String BASE_PATH = "/data/pic/";
    private static final String BASE_URL = "https://staticsource.cdqidi.cn/static/resoure/";
    private static final String MEDIA_ID_KEY = "media_id_";
    private final WxaMsgService wxaMsgService;
    private final StringRedisTemplate stringRedisTemplate;


    public void sendWxaMessage(String appId, String openId) {
        String key = MEDIA_ID_KEY + appId;
        String mediaId = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.hasLength(mediaId)) {
            String name = appId + ".jpg";
            File file = new File(BASE_PATH + name);
            if (!file.exists()) {
                saveToFile(BASE_URL + name, name);
                file = new File(BASE_PATH + name);
            }
            log.info("file: " + file);
            ApiResult result = WxaMaterialApi.uploadMedia(file, "image");
            log.info("result: " + result.getJson());
            if (result.isSucceed()) {
                mediaId = result.getStr("media_id");
                if (StringUtils.hasLength(mediaId)) {
                    stringRedisTemplate.opsForValue().set(key, mediaId, 2, TimeUnit.DAYS);
                }
            }
            log.info("mediaId: " + mediaId);
        }
        wxaMsgService.sendWxaMessage(appId, openId, TEXT_MSG, mediaId);
    }

    private void saveToFile(String destUrl, String name) {
        try {
            File f = new File(WxService.BASE_PATH);
            if (!f.exists()) {
                boolean mkDirs = f.mkdirs();
                log.info("mkDirs: " + mkDirs);
            }
            URL url = new URL(destUrl);
            HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
            try {
                httpUrl.connect();
                try (BufferedInputStream bis = new BufferedInputStream(httpUrl.getInputStream());) {
                    int size;
                    byte[] buf = new byte[1024];
                    try (FileOutputStream fos = new FileOutputStream(WxService.BASE_PATH + name)) {
                        while ((size = bis.read(buf)) != -1) {
                            fos.write(buf, 0, size);
                        }
                        fos.flush();
                    }
                }
            } finally {
                httpUrl.disconnect();
            }
        } catch (IOException | ClassCastException e) {
            throw new ApiException(e);
        }
    }
}
